from xml.dom import minidom
import linecache
import urllib
import time
import datetime
import re
def get_program(name, date):
	
	i = 1
	l = len(open('interia_ch', 'rU').readlines())
	while	i<l and linecache.getline('interia_ch',i).strip() != name.strip():
		i = i+2
	url = "http://programtv.interia.pl/feed/program," + str(linecache.getline('interia_ch',i+1)).strip()+'?sDate='+date
	sock = urllib.urlopen(url)
	program = minidom.parse(sock)
	return program

def get_title_by_time(program, tm):
	title_list = []
	hpattern = re.compile(r'^(\d{1,2}):')
	mpattern = re.compile(r':(\d{2})')
	tm = 60 * int(hpattern.search(tm).groups()[0]) + int(mpattern.search(tm).groups()[0])
	for i in program.getElementsByTagName("item"):
		title = i.getElementsByTagName("title")[0].childNodes[0].toxml()
		tm2 = 60*int(hpattern.search(title).groups()[0]) + int(mpattern.search(title).groups()[0])
		if tm2 - tm <= 10 and tm < tm2:
			title_list.append(title)
	return title_list
		
def get_length_by_title(program, title, jump=1):
	for i in program.getElementsByTagName("item"):
		if i.getElementsByTagName("title")[0].childNodes[0].toxml().strip() == title.strip():
			flag = 1
		else:
			if flag:
				jump -= 1
				if jump == 0:
					return title_to_minutes(i.getElementsByTagName("title")[0].childNodes[0].toxml())
		

